
// 获取页面query参数
export function query() {
  let pages = getCurrentPages()
  let curPage = pages[pages.length - 1]
  return curPage.options || curPage.$route.query || {}
}

export function formatSeconds(s) {
  let t = ''
  s = parseInt(s)
  if (s >= 0) {
    const hour = Math.floor(s / 3600)
    const min = Math.floor(s / 60) % 60
    const sec = s % 60
    if (hour > 0) {
      if (hour < 10) {
        t = '0' + hour + ':'
      } else {
        t = hour + ':'
      }
    }

    if (min < 10) {
      t += '0'
    }
    t += min + ':'
    if (sec < 10) {
      t += '0'
    }
    t += sec
  }
  return t
}

export function formatTime(time) {
  let date = new Date(time),
    year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate(),
    hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
    minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
    second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  month >= 1 && month <= 9 ? (month = "0" + month) : "";
  day >= 0 && day <= 9 ? (day = "0" + day) : "";
  let timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
  return timer;
}

export function formatDate(date, fmt) {
  const _d = new Date(date)
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (_d.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  let o = {
    'M+': _d.getMonth() + 1,
    'd+': _d.getDate(),
    'h+': _d.getHours(),
    'm+': _d.getMinutes(),
    's+': _d.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      )
    }
  }
  return fmt
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}

// 转换wx自带函数为Promise
export function promisify(original) {
  return function (opt) {
    return new Promise((resolve, reject) => {
      opt = Object.assign({
        success: resolve,
        fail: reject
      },
        opt
      )
      if (original) {
        original(opt)
      } else {
        reject(new Error('promisify: original is null'))
      }
    })
  }
}

// 显示toast弹窗
// icon: success, loading, none
export function showToast(content = '', icon = 'none', duration = 3000) {
  hide()
  uni.showToast({
    title: content,
    icon,
    duration: duration
  })
}

export function show(title = '加载中', mask = true) {
  hide()
  uni.showLoading({
    title,
    mask
  })
}

export function hide() {
  uni.hideLoading()
  uni.hideToast()
}

// promise弹框，简化使用方法
// example:
// let [err, res] = await to(this.$utils.showModal('是否确定要去提交？'))
// if (res && res.confirm)...
export function showModal(message, showCancel = true, title = '提示', confirmText = '确定') {
  const p = promisify(uni.showModal)
  return p({
    title,
    content: message,
    showCancel,
    confirmText
  })
}

export function timeout(time = 1000) {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

// 颜色转换
function componentToHex(c) {
  var hex = c.toString(16)
  return hex.length === 1 ? '0' + hex : hex
}

export function rgbToHex(r, g, b) {
  return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b)
}

// 整数补0
export function pad(num, n = 2) {
  var len = num.toString().length
  while (len < n) {
    num = '0' + num
    len++
  }
  return num
}

export function debounce(func, wait, immediate) {
  // immediate默认为false
  var timeout, args, context, timestamp, result

  var later = function () {
    var last = Date.now() - timestamp
    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function () {
    context = this
    args = arguments
    timestamp = Date.now()
    // 第一次调用该方法时，且immediate为true，则调用func函数
    var callNow = immediate && !timeout
    // 在wait指定的时间间隔内首次调用该方法，则启动计时器定时调用func函数
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export function checkMobile(phone) {
  return /^1[3456789]\d{9}$/.test(phone)
}

// iOS IDFA
export function idfa() {
  let idfa = ''
  // #ifdef APP-PLUS
  const ASIdentifierManager = plus.ios.importClass('ASIdentifierManager')
  const sharedManager = ASIdentifierManager.sharedManager()
  if (sharedManager.isAdvertisingTrackingEnabled()) {
    const advertisingIdentifier = sharedManager.advertisingIdentifier()
    idfa = plus.ios.invoke(advertisingIdentifier, 'UUIDString')
  }
  // #endif
  // #ifdef H5
  idfa = Math.random()
    .toString()
    .slice(2, 8)
  // #endif
  return idfa
}

// 获取App手机设备ID
export function uuid() {
  return plus.device.uuid
}

// key: 存储的key值
// 成功后保存在本地的对象{url, path}
// url: 缓存的图片url，和新的url进行对比
// path: 存储在本地图片路径
// options: 可选参数
export function imageCache(key, url, options = {}) {
  return new Promise((resolve, reject) => {
    // 先检查是否有缓存，如果没有，下载图片开始保存
    let saved = uni.getStorageSync(key)
    if (saved) {
      if (saved.url === url) {
        // 已经缓存
        resolve(saved.path)
        return
      }
    }
    // 未做缓存，开始下载缓存
    uni.downloadFile({
      url,
      success: function (res) {
        if (res.statusCode === 200) {
          // 第二步: 使用小程序的文件系统，通过小程序的api获取到全局唯一的文件管理器
          const tempFilePath = res.tempFilePath
          uni.saveFile({
            tempFilePath: tempFilePath, // 传入一个临时文件路径
            success(res) {
              const save = {
                url,
                path: res.savedFilePath,
                options
              }
              console.log(`---> cache for ${key} <---`, save)
              uni.setStorageSync(key, save)
              resolve(res.savedFilePath)
            },
            fail: reject,
          })
        } else {
          reject(new Error('下载失败'))
        }
      },
      fail: reject,
    })
  })
}

// 根据key获取图片缓存信息
export function getImageCache(key) {
  return uni.getStorageSync(key)
}

// 删除缓存图片
export function deleteImageCache(key) {
  console.log(`deleteImageCache ${key}`)
  uni.removeStorage({
    key
  })
}

/**
 * 当前日星期几
 * */
export function getDayOfWeek(date) {
  if (typeof date == 'string') {
    return new Date(date.replace(/-/gi, '/'))
  } else {
    return date
  }
}

/**
 * 对象转url参数
 * @param {*} data
 * @param {*} isPrefix add '?'
 */
export function queryParams(data, isPrefix = true) {
  const prefix = isPrefix ? '?' : ''
  const _result = []
  for (const key in data) {
    const value = data[key]
    // 去掉为空的参数
    if ([undefined, null].includes(value)) {
      continue
    }
    if (value.constructor === Array) {
      value.forEach(_value => {
        _result.push(
          encodeURIComponent(key) + '[]=' + encodeURIComponent(_value)
        )
      })
    } else {
      _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
    }
  }

  return _result.length ? prefix + _result.join('&') : ''
}

/**
 * 以下是产生后台需要的GUID格式
 * */
function s4() {
  return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
}

export function newGuid() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4()
}